<?php
class programme extends Model{
	public static function getTableName(){
		return 'programme';
	}

	public function set($object){/*{{{*/
		$this->path= !isset($object->path) ? '' : strtolower(trim($object->path));
		$this->cpl_category_id= !isset($object->cpl_category_id) ? '0' : $object->cpl_category_id;
		$this->series_id= !isset($object->series_id) ? '0' : trim($object->series_id);
		$this->number_of_episodes= !isset($object->number_of_episodes) ? '0' : trim($object->number_of_episodes);
		$this->nominal_duration= !isset($object->nominal_duration) ? null : $object->nominal_duration;
		$this->starting_original_episode_no= !isset($object->starting_original_episode_no) ? '0' : trim($object->starting_original_episode_no);
		$this->production_start_date= !isset($object->production_start_date) ? '' : $object->production_start_date;
		$this->production_end_date= !isset($object->production_end_date) ? '' : $object->production_end_date;
		$this->first_network_codes= !isset($object->first_network_codes) ? '' : $object->first_network_codes;
		$this->first_time_onair= !isset($object->first_time_onair) ? '' : $object->first_time_onair;
		#$this->first_onair_information= !isset($object->first_onair_information) ? '' : trim($object->first_onair_information);
		$this->first_episode_time_onair= !isset($object->first_episode_time_onair) ? '' : $object->first_episode_time_onair;
		$this->last_episode_time_onair= !isset($object->last_episode_time_onair) ? '' : $object->last_episode_time_onair;
		$this->publish_datetime= !isset($object->publish_datetime) ? '' : $object->publish_datetime;
		$this->expire_datetime= !isset($object->expire_datetime) ? '' : $object->expire_datetime;
		$this->meta_keywords= !isset($object->meta_keywords) ? '' : $object->meta_keywords;
		$this->meta_description= !isset($object->meta_description) ? '' : $object->meta_description;
		$this->minisite_url= !isset($object->minisite_url) ? '' : $object->minisite_url;
		$this->blog_url= !isset($object->blog_url) ? '' : trim($object->blog_url);
		$this->forum_id= !isset($object->forum_id) ? '0' : trim($object->forum_id);
		$this->average_rating= !isset($object->average_rating) ? '0' : trim($object->average_rating);
		$this->highlighted_cast_roles= !isset($object->highlighted_cast_roles) ? '' : $object->highlighted_cast_roles;
		$this->casts= !isset($object->casts) ? '' : $object->casts;
		$this->available_tag_types= !isset($object->available_tag_types) ? '' : $object->available_tag_types;
		$this->tags= !isset($object->tags) ? '' : $object->tags;
		$this->folders= !isset($object->folders) ? '' : $object->folders;
		$this->premium_flag= !isset($object->premium_flag) ? 0 : $object->premium_flag;
		$this->video_type= !isset($object->video_type) ? 'O' : $object->video_type;
		$this->telco= !isset($object->telco) ? 0 : $object->telco;
		$this->auto_publish= !isset($object->auto_publish) ? '0' : $object->auto_publish;
		$this->auto_publish_starttime = !isset($object->auto_publish_starttime) ? '' : $object->auto_publish_starttime;
		$this->auto_publish_endtime = !isset($object->auto_publish_endtime) ? '' : $object->auto_publish_endtime;
		$this->status= !isset($object->status) ? '0' : $object->status;
		$this->created_at= !isset($object->created_at) ? '' : $object->created_at;
		$this->created_by= !isset($object->created_by) ? '' : $object->created_by;
		$this->modified_at= !isset($object->modified_at) ? '' : $object->modified_at;
		$this->modified_by= !isset($object->modified_by) ? '' : $object->modified_by;
	}/*}}}*/

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx	= NULL, $sord = NULL, $unpublish = 0)
    {
        # part, where sentence
        $find	=	$findRelation['mapField'];
        $db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $searchSing =   FALSE;
        $titleWhere =   $programmeTitleIds  =   NULL;
		$cplWhere   =   NULL;
        $tvbCategory=   $tvbCategoryIds     =   NULL;
        $programmes =   array();
        $resField   =   $resOperation   =   $resValue   =   array();

        foreach ($field as $fieldKey => $fieldValue) {
            switch ($fieldValue) {
            case 'title':
                $titleWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                break;
            case 'company_code_cpl':
                $cplWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                #/*bug 3696
                $cplWhere[] = str_replace('`findApi`.company_code_cpl', 'cpl_company_code', $cplWhere[0]);
                $cplWhere[] = str_replace('`findApi`.company_code_cpl', 'cpl_id', $cplWhere[0]);
                #*/
                break;
            case 'tvbcom_category':
                if(!empty($value[$fieldKey])) {
                    $tvbCategory[] = $value[$fieldKey];
                }
                break;
            case 'premium':
                if ($value[$fieldKey] != '2') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            case 'premium_items':
                if (isset($value[$fieldKey]) && is_array($value[$fieldKey])) {
                    foreach ($value[$fieldKey] as $_value) {
                        if ($_value == 'subscription_flag') {
                            $where_extra[] = '`subscription_flag`=1';
                        } else if ($_value == 'ppv_flag') {
                            $where_extra[] = '`ppv_flag`=1';
                        }
                    }
                }
                break;
            case 'video_type':
                if ($value[$fieldKey] != 'all') { // 2=all
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
                }
                break;
            default:
                $resField[$fieldKey] = $fieldValue;
                $resOperation[$fieldKey] = $operation[$fieldKey];
                $resValue[$fieldKey] = $value[$fieldKey];
                break;
            }
        }
        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation,$db_con);
        }
        if (!empty($cplWhere))
        {
            $searchSing = TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByCPL($cplWhere, $field, $operation,$db_con);
        }
        if (!empty($tvbCategory))
        {
            $searchSing =   TRUE;
            $tvbCategory=   implode(",", $tvbCategory);
            //echo 'string :'.$tvbCategory;
            // $tvbCategory=   str_replace('tvbcom_category', 'system_label', $tvbCategory);
            # get programme ID
            $sql=   '
                SELECT  DISTINCT
                    pt.programme_id                 AS  programmeIds
                FROM
                    tvbcom_category                 AS  findApi,
                    `programme-tvbcom_category`     AS  pt
                WHERE
                    pt.category_id = findApi.id 
                    AND 
                    (
                        findApi.id IN ('. $tvbCategory .')
                        OR findApi.parent_id IN ( '.$tvbCategory . ')
                    )
                ';
            $tvbCategoryIds =	$db_con->findBySql(__class__,$sql);
            if (!empty($tvbCategoryIds[0]->programmeIds))
            {
                foreach ($tvbCategoryIds    as  $tvbObject)
                {
                    $programmesTmp[]   =   $tvbObject->programmeIds;
                }
                $programmes[]   =   $programmesTmp;
            }
            else
            {
                $programmes[]   =   array();
            }
        }
        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   

            if (empty($programmeTitleIds))  $programmeTitleIds  =   '""';
            $programmeTitleIds  =   'WHERE outProgramme.id IN ('. $programmeTitleIds. ')';   
        }

		$where = Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		if (!empty($where)) {
			$where = ' WHERE '. $where;
        } else {
            $where = ' WHERE 1';
        }

        if (!empty($where_extra)) {
            $where .= ' AND ' . implode(' AND ', $where_extra);
        }


		$subSql =	'
            SELECT DISTINCT
                outProgramme.id AS	id,
                outProgramme.path AS	path,
                GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")	AS	title,
                (
                    SELECT DISTINCT
                    GROUP_CONCAT(TC.id SEPARATOR ",")
                    FROM
                    `programme-tvbcom_category`	AS PT,
                    tvbcom_category				AS TC,
                    programme					AS PR
                    WHERE
                    TC.id = PT.category_id
                    AND PR.id = PT.programme_id
                    AND PR.id = outProgramme.id 
                ) AS	tvbcom_category,
                (
                    SELECT DISTINCT
                    GROUP_CONCAT(concat(inSubCpl.cpl_company_code, " ", inSubCpl.cpl_id) SEPARATOR "<br />")
                    FROM
                    programme_cpl	AS inSubCpl
                    WHERE
                    inSubCpl.programme_id = outProgramme.id
                ) AS	company_code_cpl,
                outProgramme.status AS  record_status,
                outProgramme.modified_at AS	modified_at,
                outProgramme.modified_by AS	modified_by,
                outProgramme.premium_flag AS premium,
                outProgramme.video_type,
                `programme_premium`.ppv_flag,
                `programme_premium`.subscription_flag
            FROM programme AS outProgramme
            LEFT JOIN `programme_premium` ON (`programme_premium`.programme_id = outProgramme.id)
            LEFT JOIN `programme-language` ON (`programme-language`.programme_id = outProgramme.id)
            '. $programmeTitleIds. '
            GROUP BY id
        ';

		$sql=	'
			SELECT
				id,
				path,
				title,
				tvbcom_category,
                record_status,
				modified_at,
				modified_by,
				company_code_cpl
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# condition : category ID 
		#if (empty($_REQUEST['catL3']))
		#{
		#	$sql	.=	' AND (`programme-cpl_category`.`category_id` <> 0 OR `programme-cpl_category`.category_id is null) ';
		#}
		#else
		#{
		#	$sql	.=	' AND (`programme-cpl_category`.`category_id` = '. $_REQUEST['catL3']. ') ';
		#}

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                $orderBy[]  =   $find[$value];
            }
        }

        $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)/*{{{*/
		{
			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);
			#preg_replace($gridData['title']);
			#$gridData['title'] = htmlentities($gridData['title']);

			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();

            # set record_status display name
            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                $publish_log = publish_log::getPublishLog(__class__, $gridData->id);
                if (property_exists($publish_log, 'non_premium')) {
                    $publish = Model::object2array($publish_log->non_premium); 
                } else {
                    $publish = array();
                }

                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }

            # set TVB.COM Category display
            $tvbcomArray    =   array();
            if (!empty($gridData->tvbcom_category))
            {
                $tvbcom_categoryIDs =   explode(',', $gridData->tvbcom_category);
                if (is_array($tvbcom_categoryIDs))
                {
                    foreach ($tvbcom_categoryIDs    as  $ID)
                    {
                        $temp   =   tvbcom_category::getParentChildName($ID);
                        if (empty($temp->child))    continue;
                        if (empty($temp->parent))
                        {
                            $tvbcomArray[]  =   $temp->child;
                        }
                        else
                        {
                            $tvbcomArray[]  =   $temp->parent. ' '. $temp->child;
                        }
                    }
                    $gridData->tvbcom_category  =   implode('<br />', $tvbcomArray);
                }
            }

            # assemble data to array return
			foreach ($find as $name => $column) {
                switch ($name) {
                case 'premium':
                case 'premium_items':
                case 'video_type':
                    break;
                default:
                    $tmp['cell'][]	=	$gridData->$name;
                }
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED  !=  $originalStatus &&  empty($unpublish))
            {
                $delEdit    =	'<a title="Edit" href="get_programme.html?act=edit&step=2&id='. $gridData->id. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_programme.html?act=view&step=2&id='. $gridData->id. '&unpublish='. $unpublish .'" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $tmp['cell'][]  =   $delEdit. $delView;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}/*}}}*/
		return	$list;
	}

	public function getDetails($programme_id)
	{
		//in the future
		//$sql = "select * from ".self::getTableName()." a left join `programme-language` b on a.id=b.programme_id left join programme_cpl c on b.programme_id=c.programme_id where a.id={$programme_id}";
		$sql = "
			select 
				group_concat(title SEPARATOR '\n\t') as mix_programme_name,
				group_concat(settop_box_name SEPARATOR '\n\t') as mix_settop_box_name,
				a.*,
				b.* 
			from programme a 
				left join `programme-language` b on a.id=b.programme_id 
			where programme_id='{$programme_id}'
			group by programme_id
		";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);

        $sql = "SELECT * FROM `programme-language` WHERE `programme_id` = " . $programme_id;
        $ro = Model::$dbo['r']->findBySql(__class__, $sql);
        foreach ($ro as $key=>$obj) {
            $programme_language[$obj->language_id] = $obj;
        }

        $ret[0]->programme_language = $programme_language;
		return isset($ret[0]) ? $ret[0] : "";
	}

	public function getList($lang_id)
	{
		$sql = "select * from ".self::getTableName()." a left join `programme-language` b on a.id=b.programme_id left join programme_cpl c on b.programme_id=c.programme_id where b.language_id={$lang_id}";
		return Model::$dbo['r']->findBySql(__class__, $sql);
	}

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id,$premium=false)
    {
        if (empty($id)) return  array();
        $sqlArr =   array(
                    'programme'                 =>  array('id = "'. $id. '"'),
                    'programme-language'        =>  array('programme_id = "'. $id. '"'),
                    'programme-tvbcom_category' =>  array('programme_id = "'. $id. '" ORDER BY rank'),
                    'programme_cpl'             =>  array('programme_id = "'. $id. '"'),
                    'programme_clone'           =>  array('programme_id = "'. $id. '"'),
                );

		if($premium){
			$sqlArr['programme']              = array('id = "'. $id. '"');
			$sqlArr['programme_premium']      = array('programme_id = "'.$id.'"');
			$sqlArr['programme_ppv']          = array('programme_id = "'.$id.'"');
			$sqlArr['programme_subscription'] = array('programme_id = "'.$id.'"');
		}

        $sqlArray   =   array();
        foreach ($sqlArr    as  $tableName  =>  $whereArray)
        {
            $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }

	/**
	 * check path duplicated
	 *
	 * @param $path
	 * @return bool : true duplicated; false not
	 */
	public static function checkPath($path)
	{
		#$sql = "select * from ".self::getTableName()." where path='{$path}'";
		#$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		#return isset($ret[0]) ? $ret[0]->id : false;

		$sql = 'SELECT id FROM programme WHERE path=:path';
		$ret = Model::selectBySql($sql, array(':path'=>$path));
		return isset($ret[0]['id']) ? $ret[0]['id'] : false;
	}

	public function getAutoPublish()
	{
		$sql = '
			SELECT * FROM programme
			WHERE auto_publish=1 AND auto_publish_starttime <= now() AND auto_publish_endtime >= now() 
			AND status <> '.AC::STATUS_DELETED;
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		return isset($ret[0]) ? $ret : array();
	}

	public static function isDramaProgramme($programme_id){
		$sql = "
			SELECT * FROM `programme-tvbcom_category` WHERE programme_id = '$programme_id' AND category_id IN (
				SELECT DISTINCT id FROM tvbcom_category WHERE id IN (
					SELECT DISTINCT tvbcom_category_id FROM cpl_category WHERE parent_id = (
						SELECT id FROM cpl_category WHERE system_label = 'drama' AND parent_id = 0 LIMIT 1
					)
				)
			)
			";
		$ret = Model::selectBySql($sql);
		return (bool)$ret;
	}

    public function getAutoPublishList($start, $length, $sidx, $sord)
    {
        $today = date('Y-m-d');
        $sql = 'select 
            p.id,
            pl_cn.title as title_cn,
            pl_en.title as title_en,
            p.publish_datetime,
            p.expire_datetime,
            p.status
            from programme as p
            LEFT JOIN `programme-language` as pl_cn ON pl_cn.programme_id = p.id and pl_cn.language_id =1
            LEFT JOIN `programme-language` as pl_en ON pl_en.programme_id = p.id and pl_en.language_id =2
            where auto_publish = 1 and publish_datetime >= :today order by publish_datetime ASC';
        $ret = Model::selectBySql($sql,array(':today'=>$today));
        $list = array();
        if($ret)
        {
            $Edit = $View = '';
            foreach($ret as $programme)
            {
                $originalStatus =   $programme['status'];
                $publish_log = publish_log::getPublishLog(__class__, $programme['id']);
                if (property_exists($publish_log, 'non_premium')) {
                    $publish = Model::object2array($publish_log->non_premium); 
                } else {
                    $publish = array();
                }
                if (AC::STATUS_DELETED  !=  $originalStatus)
                {
                    $Edit = '<a title="Edit" href="get_programme.html?act=edit&step=2&id='. $programme['id']. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
                }
                $View = '<a title="View" href="get_programme.html?act=view&step=2&id='. $programme['id']. '&unpublish=0" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';

                $title = $programme['title_cn'].'<br/>'.$programme['title_en'];
                $tmp            =   array();
                $tmp['cell'][] = $programme['id'];
                $tmp['cell'][] = $title;
                $tmp['cell'][] = $programme['status'];
                $tmp['cell'][] = $programme['publish_datetime'];
                $tmp['cell'][] = $programme['expire_datetime'];
                $tmp['cell'][]  =   $Edit. $View;
                $list['rows'][] =   $tmp;                
            }
        }
        return $list;
    }

	/*
	 * by donald
	 * at 2011-09-14
	 * last modified at 2011-11-07
	 */
	public function publish($programme_id)
	{
		$programme_clone_list = programme_clone::getAll(
			array(
				'programme_id' => $programme_id
			)
		);
		foreach ($programme_clone_list as $programme_clone) {
			$publish_log_detail = publish_log::getNonPremiumPublishLog('programme', $programme_clone->parent_id);
			if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH) {
				return '0208';
			}

			$programme = new programme;
			$programme_detail = $programme->get($programme_clone->parent_id);
			if ($programme_detail->premium_flag) {
				$publish_log_detail = publish_log::getPremiumPublishLog('programme', $programme_clone->parent_id);
				if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH_PREMIUM) {
					return '0208';
				}
			}
		}

		$programme = new programme();
		$programme = $programme->get($programme_id);

		$proof = new ProofreadSend();
		$flag_ready = CommonUtils::isAllVideosReady($programme->folders);
		if ($flag_ready) {
			$log_id = CommonUtils::save_log('programme', $programme_id, AC::LOG_OP_PUBLISHING, json_encode($programme));

			$publish_log_detail = publish_log::getNonPremiumPublishLog('programme', $programme_id);
			if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH) {
				$proof_flag = $proof->getProofread(Model::$dbo['r']->getDbHandle(), 'programme', $programme_id, $log_id);
				if ($proof_flag !== TRUE) {
					return $proof_flag;
				}

				$publish_type = 'old';
			} else {
				$publish_type = 'new';
			}

			if (CommonUtils::isPremiumProgramme('programme',$programme_id)){
				$publish_log_detail = publish_log::getPremiumPublishLog('programme', $programme_id);
				if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH_PREMIUM) {
					$proof = new P_ProofreadSend();
					$proof_flag = $proof->getProofread(Model::$dbo['r']->getDbHandle(), 'programme', $programme_id, $log_id);
					if ($proof_flag !== TRUE) {
						return $proof_flag;
					}

					$publish_type .= 'old';
				} else {
					$publish_type .= 'new';
				}
			}

			//new flow
			if ($publish_type != 'old' && $publish_type != 'oldold') {
				$proof = new NewProofreadSend;
				$proof_flag = $proof->getProofread(
					Model::$dbo['r']->getDbHandle(), 
					'programme', 
					$programme_id, 
					$log_id,
					TRUE,
					$publish_type
				);
			}

			//remove change_log if go old flow
			switch ($publish_type) {
				case 'old':
				case 'oldold':
				case 'oldnew':
				case 'newold':
					change_log::remove(array('programme_id' => intval($programme_id)));
					break;
				default:
					break;
			}
		} else {
			$proof_flag = '0202';
		}

		return $proof_flag;
	}

	/*
	 * by donald
	 * at 2011-09-22
	 */
	public static function getProgrammeIdForChangeLog($folder_id, $programme_id)
	{
		$programme = new programme;
		$programme_detail = $programme->get($programme_id);

		$folders[] = $programme_detail->folders;

		$casts = json_decode($programme_detail->casts, TRUE);
		foreach ($casts as $cast_list) {
			foreach ($cast_list as $cast) {
				$cast_id = $cast['cast_id'];
				if (!empty($cast_id)) {
					$cast = new cast;
					$cast_detail = $cast->get($cast_id);
					if (!empty($cast_detail->folders)) {
						$folders[] = $cast_detail->folders;
					}
				}
			}
		}

		$folders = explode(',', implode(',', $folders));

		return in_array($folder_id, $folders) ? $programme_id : 0;
	}

	/*
	 * by donald
	 * at 2011-11-04
	 */
	public static function delete($programme_id)
	{
		$programme_clone_list = programme_clone::getAll(
			array(
				'parent_id' => $programme_id
			)
		);

		foreach ($programme_clone_list as $programme_clone) {
			self::delete($programme_clone->programme_id);
		}

		$programme = new programme();
		$programme = $programme->get($programme_id);

		if ($programme->status == AC::STATUS_DELETED) {
			return;
		}

		$programme->status = AC::STATUS_DELETED;
		$programme->modified_at = date("Y-m-d H:i:s");
		$programme->modified_by = CommonUtils::get_user();
		$programme->update();

		$audit_log = new audit_log;
		$audit_log->item_type_id = item_type::getItemIDByName('programme');
		$audit_log->item_id = $programme_id; 
		$audit_log->modified_at = date("Y-m-d H:i:s");
		$audit_log->modified_by = CommonUtils::get_user();
		$audit_log->status = AC::STATUS_DELETED; 
		$audit_log->remarks = 'programme delete success'; 
		$audit_log->action = AC::LOG_OP_DELETE; 
		$audit_log->data = json_encode($programme);
		$audit_log->insert();

		change_log::remove(
			array(
				'programme_id' => intval($programme_id)
			)
		);
	}

	/*
	 * by donald
	 * at 2011-11-04
	 */
	public static function unpublish($programme_id)
	{
		$programme_clone_list = programme_clone::getAll(
			array(
				'parent_id' => $programme_id
			)
		);
		foreach ($programme_clone_list as $programme_clone) {
			// unpublish children programme first
			self::unpublish($programme_clone->programme_id);
		}

		$publish_log_detail = publish_log::getNonPremiumPublishLog('programme', $programme_id);
		if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH) {
			// not published before or is unpublished
			return;
		}

		$programme = new programme();
		$programme = $programme->get($programme_id);

		$log_id = CommonUtils::save_log('programme', $programme_id, AC::LOG_OP_UNPUBLISHING, json_encode($programme));
		Unpublished::send('programme', $programme_id, $programme_id, $log_id);
	}

	/*
	 * by donald
	 * at 2011-11-04
	 */
	public static function p_unpublish($programme_id)
	{
		$programme_clone_list = programme_clone::getAll(
			array(
				'parent_id' => $programme_id
			)
		);
		foreach ($programme_clone_list as $programme_clone) {
			// unpublish children programme first
			self::p_unpublish($programme_clone->programme_id);
		}

		$publish_log_detail = publish_log::getPremiumPublishLog('programme', $programme_id);
		if (empty($publish_log_detail) || $publish_log_detail->status == AC::STATUS_UNPUBLISH_PREMIUM) {
			// not published before or is unpublished
			return;
		}

		$programme = new programme();
		$programme = $programme->get($programme_id);

		$log_id = CommonUtils::save_log('programme', $programme_id, AC::LOG_OP_PREMIUM_UNPUBLISHING, json_encode($programme));
		P_Unpublished::send('programme', $programme_id, $programme_id, $log_id);
	}

}
?>
